﻿using Model;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ZBZH_Manage_Order.Models;
using ZBZH_Manage_Order.PublicMethod;

namespace ZBZH_Manage_Order.Controllers.WaterManagement
{
    public class FlowPayController : Controller
    {
        //
        // GET: /FlowPay/ 
        ServiceReference1.Service1Client wsdcser = new ServiceReference1.Service1Client();
        ZHHQSERVICE.Service1Client service = new ZHHQSERVICE.Service1Client();
       
        public ActionResult Index()
        {
            return View();
        }

        #region 获取第三方支付流水到datagrid
        /// <summary>
        /// 获取第三方支付流水到datagrid
        /// </summary>
        /// <param name="jqgridparam"></param>
        /// <returns></returns>
        public ActionResult getflowp(JqGridParam jqgridparam)
        {
            try
            {
                Page<FlowPay> page = new Page<FlowPay>();//分页类定义
                List<FlowPay> list = new List<FlowPay>();//定义第三方流水视图表
                list = GetAllPay(jqgridparam);//解析返回的结果
                if (list.Count > 0)//返回结果正常
                {
                    jqgridparam.records = list.Count;//查询的数据总数
                    var data = new
                    {
                        total = list.Count.ToString(),
                        rows = list//返回当前页的数据
                    };
                    return Json(data, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    var data = new
                    {
                        total =0,
                        rows = list
                    };
                    return Json(data, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }
        #endregion

        #region 获取所有流水
        /// <summary>
        /// 获取所有流水
        /// </summary>
        /// <returns></returns>
        public List<FlowPay> GetAllPay(JqGridParam jqgridparam)
        {
            List<FlowPay> list = new List<FlowPay>();
            string result = wsdcser.GetOrder_FlowPay(jqgridparam.page, jqgridparam.rows, "", 1);
            JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
            string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
            if (bs == "1")//返回结果正常
            {
                IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                list = ParseClass<FlowPay>.JsonList(jieguo);//解析返回的结果
            }
            return list;
                 #region
            //    if (jieguo.Count > 0)
            //    {
            //        foreach (JToken item in jieguo)
            //        {
            //            List<FlowPay> newlist = new List<FlowPay>();
            //            FlowPay m = new FlowPay();
            //            m.AccID = int.Parse(item["AccID"].ToString());
            //            m.AccName = item["AccName"].ToString();
            //            m.FlowPayID = item["FlowPayID"].ToString();
            //            m.PayFlowTypeName = item["PayFlowTypeName"].ToString();
            //            m.OrdrID = item["OrdrID"].ToString();
            //            m.PayID = item["PayID"].ToString();
            //            m.PayBZ = item["PayBZ"].ToString();
            //            m.PayFlowOper = int.Parse(item["PayFlowOper"].ToString());
            //            m.PayFlowTime = item["PayFlowTime"].ToString();
            //            m.PayFlowType = item["PayFlowType"].ToString();
            //            m.PayHaveNub = DataHelper.MoneyToYuang(item["PayHaveNub"].ToString());
            //            m.PayName = item["PayName"].ToString();
            //            m.AccCall = item["AccCall"].ToString();
            //            m.AccCerNub = item["AccCerNub"].ToString();
            //            m.AccCerType = item["AccCerType"].ToString();
            //            m.AccCerType_DicName_Login = item["AccCerType_DicName_Login"].ToString();
            //            m.AccIdentifier = item["AccIdentifier"].ToString();
            //            m.OperNum = item["OperNum"].ToString();
            //            m.AccNum = item["AccNum"].ToString();
            //            m.AccSex = int.Parse(item["AccSex"].ToString());
            //            m.CategoryID = item["CategoryID"].ToString();
            //            m.DepID = item["DepID"].ToString();
            //            m.DepID_DepName_Department = item["DepID_DepName_Department"].ToString();
            //            m.IdentityID = item["IdentityID"].ToString();
            //            m.IdentityID_DiName_SystemIdentity = item["IdentityID_DiName_SystemIdentity"].ToString();
            //            m.PayOherID = item["PayOherID"].ToString();
            //            m.SataeID = item["SataeID"].ToString();
            //            m.StateID_DicName_SystemIdentity = item["StateID_DicName_SystemIdentity"].ToString();
            //            list.Add(m);
            //        }
            //    }
            //    return list;
            //}
            //else
            //{
            //    return null;
            //}
                 #endregion

        }
        #endregion

        #region 获取证件类型
        /// <summary>
        /// 获取证件类型
        /// </summary>
        /// <returns></returns>
        public ActionResult getacccertype()
        {
            List<Basic_Dict_T> ls = new List<Basic_Dict_T>();
            ls = PublicMethod.GetDict.GetList(18);
            return Json(ls, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 获取流水类型
        /// <summary>
        /// 获取流水类型
        /// </summary>
        /// <returns></returns>
        public ActionResult getpayflowtype()
        {
            List<Basic_Dict_T> ls = new List<Basic_Dict_T>();
            ls = PublicMethod.GetDict.GetList(30);
            return Json(ls, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 获取组织结构
        /// <summary>
        /// 获取组织结构
        /// </summary>
        /// <returns></returns>
        public ActionResult getdep()
        {
            try
            {
                Model.View_OperUser user = (Model.View_OperUser)Session[SessionStorage.OperUser];

                if (user == null)
                {
                    return RedirectToAction("LoginPage", "Login");  //czx:修改为登录者的Session异常时，直接跳转到登录页面
                }

                List<TreeJsonEntity> TreeList = new List<TreeJsonEntity>();
                //int uid= user.OperID;
                string result = service.GetDepatMentNoValidate(GetYZM._YZM, 1);
                Model.DataResult dr = ParseClass<Model.DataResult>.StrDeserialize(result, 1);
                List<ZBZH_Manage_Order.Models.Basic_Department_T> ls = new List<ZBZH_Manage_Order.Models.Basic_Department_T>();
                JObject jb = JObject.Parse(result);
                if (jb["BS"].ToString() == "1")//返回结果正常
                {
                    IList<JToken> jieguo = jb["rows"].Children().ToList();
                    ls = ParseClass<ZBZH_Manage_Order.Models.Basic_Department_T>.JsonList(jieguo);//解析返回的结果
                    foreach (ZBZH_Manage_Order.Models.Basic_Department_T item in ls)
                    {
                        bool hasChildren = false;
                        IList childnode = ls.FindAll(t => t.DepParentID == item.DepID);
                        if (childnode.Count > 0)
                        {
                            hasChildren = true;
                        }
                        TreeJsonEntity tree = new TreeJsonEntity();
                        tree.id = item.DepID;
                        tree.text = item.DepName;
                        tree.value = item.DepID;
                        tree.isexpand = true;
                        tree.complete = true;
                        tree.hasChildren = hasChildren;
                        tree.parentId = item.DepParentID;
                        TreeList.Add(tree);
                    }
                    string a = TreeList.TreeToJson();
                    return Content(TreeList.TreeToJson());
                }
                else
                {
                    return Json(jb["Msg"].ToString());
                }
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }
        #endregion

        #region 获取支付渠道
        /// <summary>
        /// 获取支付渠道
        /// </summary>
        /// <returns></returns>
        public ActionResult getpayname()
        {
            try
            {
                List<Model.Order_Pay_T> list = new List<Model.Order_Pay_T>();//定义钱包
                string result = wsdcser.GetOrder_Pay("", 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")//返回结果正常
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                    if (jieguo.Count > 0)
                    {
                        foreach (JToken item in jieguo)
                        {
                            Model.Order_Pay_T m = new Model.Order_Pay_T();
                            m.PayID = item["PayID"].ToString();
                            m.PayName = item["PayName"].ToString();
                            list.Add(m);
                        }
                    }
                    return Json(list, JsonRequestBehavior.AllowGet);
                }
                return Json(searcho["Msg"].ToString());
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }
        #endregion

        #region 旧查询第三方支付流水
       // public ActionResult SearchPay(string AccName, string AccCall, string AccID, string AccCerType, string AccCerNub, string DepID, string PayFlowType, string PayID, string PayFlowTime, JqGridParam jqgridparam)
       //{
       //    try
       //    {
       //        //Page<FlowPay> page = new Page<FlowPay>();//
       //        List<FlowPay> ls = GetAllPay(jqgridparam);
       //        List<FlowPay> newls = new List<FlowPay>();//
       //        if (ls.Count != 0)
       //        {
       //            if (AccName != "")
       //            {
       //                ls = ls.Where(i => i.AccName.Contains(AccName)).ToList();
       //            }
       //            if (AccCall != "")
       //            {
       //                ls = ls.Where(i => i.AccCall.Contains(AccCall)).ToList();
       //            }
       //            if (AccID != "")
       //            {
       //                ls = ls.Where(i => i.AccID.ToString().Contains(AccID)).ToList();
       //            }
       //            if (AccCerType != "")
       //            {
       //                ls = ls.Where(i => i.AccCerType == AccCerType).ToList();
       //            }
       //            if (AccCerNub != "")
       //            {
       //                ls = ls.Where(i => i.AccCerNub.Contains(AccCerNub)).ToList();
       //            }
       //            if (DepID != "undefined")
       //            {
       //                ls = ls.Where(i => i.DepID == DepID).ToList();
       //            }
       //            if (PayFlowType != "")
       //            {
       //                ls = ls.Where(i => i.PayFlowType == PayFlowType).ToList();
       //            }
       //            if (PayID != "")
       //            {
       //                ls = ls.Where(i => i.PayID == PayID).ToList();
       //            }
       //            if (PayFlowTime != "")
       //            {
       //                PayFlowTime = PayFlowTime.Replace("-", "");
       //                ls = ls.Where(i => i.PayFlowTime.IndexOf(PayFlowTime) > -1).ToList();
       //            }
       //            jqgridparam.records = ls.Count;//查询的数据总数
       //            var data = new
       //            {
       //                total = ls.Count,
       //                rows = ls//返回当前页的数据 
       //            };
       //            return Json(data, JsonRequestBehavior.AllowGet);
       //        }

       //        else
       //        {
       //            jqgridparam.records = ls.Count;//查询的数据总数
       //            var data = new
       //            {
       //                total = 0,
       //                rows = ls//返回当前页的数据 
       //            };
       //            return Json(data, JsonRequestBehavior.AllowGet);
       //        }
       //    }
       //    catch (Exception)
       //    {
       //        return null;
       //    }
       // }
        #endregion

        #region 查询第三方支付流水
        public ActionResult SearchPay(string AccName, string AccCall, string AccID, string AccCerType, string AccCerNub, string DepID, string PayFlowType, string PayID, string PayFlowTime,string EFlowTime, JqGridParam jqgridparam)
        {
            try
            {
                List<FlowPay> list = new List<FlowPay>();
                PayFlowTime = PayFlowTime.Replace("-", "");
                EFlowTime = EFlowTime.Replace("-", "");
                string result = wsdcser.GetOrder_FlowPayByPara(jqgridparam.page, jqgridparam.rows, AccName, AccCall, AccID, PayFlowType, PayID, PayFlowTime, EFlowTime, GetYZM._YZM, 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")//返回结果正常
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                    list = ParseClass<FlowPay>.JsonList(jieguo);//解析返回的结果
                    for (int t = 0; t < list.Count; t++)
                    {
                        string gg = list[t].PayFlowTime.ToString();
                        if (list[t].PayFlowTime.ToString().Length == 14)
                        {
                            list[t].PayFlowTime = gg.Substring(0, 4) + "/" + gg.Substring(4, 2) + "/" + gg.Substring(6, 2) + " " + gg.Substring(8, 2) + ":" + gg.Substring(10, 2) + ":" + gg.Substring(12, 2);
                        }
                        else
                        {
                            list[t].PayFlowTime = gg.Substring(0, 4) + "/" + gg.Substring(4, 2) + "/" + gg.Substring(6, 2) + " " + gg.Substring(8, 2) + ":" + gg.Substring(10, 2);
                        }
                         
                    }
                    var data = new
                    {
                        total = searcho["total"].ToString(),
                        rows = list
                    };
                    return Json(data);
                }
                else {
                    var data = new
                    {
                        total = "0",
                        rows = list
                    };
                    return Json(data);
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion

        //#region 获取当前页数据
        ///// <summary>
        ///// 获取当前页数据
        ///// </summary>
        ///// <param name="list">总的list数据</param>
        ///// <param name="jqgridparam">分页参数</param>
        ///// <returns></returns>
        //public List<Model.View_FlowPay> FindListPage(List<Model.View_FlowPay> list, ref JqGridParam jqgridparam)
        //{
        //    try
        //    {
        //        List<Model.View_FlowPay> RetList = new List<Model.View_FlowPay>();
        //        string orderField = jqgridparam.sort;//排序列
        //        string orderType = jqgridparam.order;//排序方式
        //        int pageIndex = jqgridparam.page;//当前页
        //        int pageSize = jqgridparam.rows;//每页行数
        //        int totalRow = jqgridparam.records;//总记录数
        //        int lastIndex = pageIndex * pageSize;//当前页最后一行
        //        if (orderType == "asc")
        //        {
        //            list = (from p in list orderby orderField ascending select p).ToList();
        //        }
        //        else if ((orderType == "desc"))
        //        {
        //            list = (from p in list orderby orderField descending select p).ToList();
        //        }

        //        //如果总行数小于当前页最后一行时 当前页最后一行等于总行数
        //        if (totalRow < lastIndex)
        //        {
        //            lastIndex = totalRow;
        //        }
        //        int fistIndex = (pageIndex - 1) * pageSize;
        //        int j = 0;
        //        for (int i = fistIndex; i < lastIndex; i++)
        //        {
        //            j++;
        //            RetList.Add(list[i]);
        //        }
        //        return RetList;
        //    }
        //    catch (Exception)
        //    {
        //        return null;
        //    }
        //}
        //#endregion

        #region 金额流水信息类定义（用于金额转换）
        /// <summary>
        /// 金额流水信息类定义（用于金额转换）
        /// </summary>
        public class FlowPay
        {
            public string AccCall { get; set; }
            public string AccCerNub { get; set; }
            public string AccCerType { get; set; }
            public string AccCerType_DicName_Login { get; set; }
            public int AccID { get; set; }
            public string AccIdentifier { get; set; }
            public string AccName { get; set; }
            public string AccNum { get; set; }
            public int? AccSex { get; set; }
            public string CategoryID { get; set; }
            public string DepID { get; set; }
            public string DepID_DepName_Department { get; set; }
            public string FlowPayID { get; set; }
            public string IdentityID { get; set; }
            public string IdentityID_DiName_SystemIdentity { get; set; }
            public string OperNum { get; set; }
            public string OrdrID { get; set; }
            public string PayBZ { get; set; }
            public int? PayFlowOper { get; set; }
            public string PayFlowTime { get; set; }
            public string PayFlowType { get; set; }
            public string PayFlowTypeName { get; set; }
            public string PayHaveNub { get; set; }
            public string PayID { get; set; }
            public string PayName { get; set; }
            public string PayOherID { get; set; }
            public string SataeID { get; set; }
            public string StateID_DicName_SystemIdentity { get; set; }
        }
        #endregion

        

        /// <summary>    
        /// 将集合类转换成DataTable    
        /// </summary>    
        /// <param name="list">集合</param>    
        /// <returns></returns>    
        public  DataTable ToDataTableTow(IList<FlowPay> list)
        {
            DataTable result = new DataTable();
            if (list.Count > 0)
            {
                PropertyInfo[] propertys = list[0].GetType().GetProperties();
                try
                {
                    foreach (PropertyInfo pi in propertys)
                    {
                        result.Columns.Add(pi.Name, pi.PropertyType);
                    }
                }
                catch (Exception ex){
                
                }
                for (int i = 0; i < list.Count; i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in propertys)
                    {
                        object obj = pi.GetValue(list[i], null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    result.LoadDataRow(array, true);
                }
            }
            return result;
        }

         
        

        public ActionResult WriteExcel(string AccName, string AccCall, string AccID, string AccCerType, string AccCerNub, string DepID, string PayFlowType, string PayID, string PayFlowTime,string EFlowTime)
        {
            string strName = "第三方流水表";
            //string strPath = "D:\\" + strName + ".csv";
            string strPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + strName + ".csv";
            try
            {
                string path = "";
                List<DataRow> rowdt = new List<DataRow>();
               
                DataTable  dt = new DataTable ();
                List<FlowPay> list = new List<FlowPay>();
                PayFlowTime = PayFlowTime.Replace("-", "");
                string result = wsdcser.GetOrder_FlowPayByPara(1,1000, AccName, AccCall, AccID, PayFlowType, PayID, PayFlowTime, EFlowTime, GetYZM._YZM, 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")//返回结果正常
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                    //list = ParseClass<FlowPay>.JsonList(jieguo);//解析返回的结果
                    IList<FlowPay> li = ParseClass<FlowPay>.JsonList(jieguo);//解析返回的结果
                    for (int t = 0; t < li.Count; t++)
                    {
                        
                        if(li[t].AccSex!=null){
                            list.Add(li[t]);
                           
                        }
                       

                    }
                    dt = ConvertToDataSet<FlowPay>(list);
                    FileInfo fi = new FileInfo(strPath);
              if (!fi.Directory.Exists)
              {
               fi.Directory.Create();
              }
           //先打印标头
            StringBuilder strColu=new StringBuilder();
            StringBuilder strValue=new StringBuilder();
            int i=0;
                  

            //StreamWriter sw = new StreamWriter(new FileStream(strPath, FileMode.CreateNew), Encoding.GetEncoding("GB2312"));
            FileStream fs = new FileStream(strPath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
           //StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
           StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
                for( i=0;i<=dt.Columns.Count-1;i++)
                {
                    strColu.Append(dt.Columns[i].ColumnName);
                    strColu.Append(",");
                }
                strColu.Remove(strColu.Length-1,1);//移出掉最后一个,字符

                sw.WriteLine(strColu);

                foreach(DataRow dr in dt.Rows)
                {
                    strValue.Remove(0,strValue.Length);//移出
        
                    for(i=0;i<=dt.Columns.Count-1;i++)
                    {
                        if (dt.Columns[i].ToString() == "PayFlowTime") {
                            string gg = dr[i].ToString();
                            if (dr[i].ToString().Length == 14)
                            {
                                dr[i] = gg.Substring(0, 4) + "/" + gg.Substring(4, 2) + "/" + gg.Substring(6, 2) + " " + gg.Substring(8, 2) + ":" + gg.Substring(10, 2) + ":" + gg.Substring(12, 2);
                            }
                            else
                            {
                                dr[i]= gg.Substring(0, 4) + "/" + gg.Substring(4, 2) + "/" + gg.Substring(6, 2) + " " + gg.Substring(8, 2) + ":" + gg.Substring(10, 2);
                            }
                        };
                        strValue.Append(dr[i].ToString());
                        strValue.Append(",");
                    }
                    strValue.Remove(strValue.Length-1,1);//移出掉最后一个,字符
                    sw.WriteLine(strValue);
                }
                
                sw.Close();
           
           

            System.Diagnostics.Process.Start(strPath);
                
 
                    #region
                    //DataTable bt = new DataTable(typeof(FlowPay2).Name);
                    //System.Reflection.PropertyInfo[] myPropertyInfo =
                    //typeof(FlowPay2).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
                    //DataRow g = bt.NewRow();
                    //for (int i = 0; i < myPropertyInfo.Length; i++)
                    //{
                    //    System.Reflection.PropertyInfo pi = myPropertyInfo[i];
                    //    String name = pi.Name;
                    //    g[name] = name; 
                    //}
                    //rowdt.Add(g);


                    //for (int e = 0; e < rowdt.Count;e++ )
                    //{
                    //    dt.Rows.Add(rowdt[e]);
                    //}
                    
                    //ds.Tables.Add(dt);
                   
                    
                    //DataTable b = ds.Tables[0];
                    //int rows= b.Rows.Count;
                    //int count = b.Columns.Count;
                    //if(count==0){
                    //    var dat  = new
                    //    {
                    //        path = "没有数据！",
                    //        msg = "1",
                    //    };
                    //    return Json(dat);
                    //}
                    
                    //string str = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                    // path = str+"第三方流水表的数据";

                    // Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
                    // excel.Application.Workbooks.Add(true);
                    // excel.Visible =true;
                     
                    // for (int c = 0; c < rows;c++ )
                    // {
                    //     if (c == 0)
                    //     {
                    //         System.Threading.Thread.Sleep(8 * 1000);
                    //     }
                    //     for (int j = 0; j < count;j++ )
                    //     {
                             
                    //         if (c == 0)
                    //         {     
                    //            excel.Cells[1, j + 1] = (object)ds.Tables[0].Columns[j].ColumnName.ToString();
                                
                    //         }
                    //         else {
                                 
                    //             if (j == 19)
                    //             {
                    //                 string t = "";
                    //                 string gg = b.Rows[c].ItemArray[j].ToString();
                    //                 if (b.Rows[c].ItemArray[j].ToString().Length == 14)
                    //                 {
                    //                     t = gg.Substring(0, 4) + "-" + gg.Substring(4, 2) + " " + gg.Substring(6, 2) + ":" + gg.Substring(8, 2) + " " + gg.Substring(10, 4);
                    //                 }
                    //                 else
                    //                 {
                    //                     t = gg.Substring(0, 4) + "-" + gg.Substring(4, 2) + " " + gg.Substring(6, 2) + ":" + gg.Substring(8, 2);
                    //                 } 
                    //                 excel.Cells[c + 1, j + 1] = (object)t;
                    //             }
                    //             else {
                    //                 excel.Cells[c + 1, j + 1] = b.Rows[c].ItemArray[j];
                                 
                    //             }
                                 
                             
                    //         }
                           
                             
                    //     }
                    // }
                    #endregion
                 
                }
                var datas=new 
                {
                    path = " 导出成功!" + strPath, 
                    msg="1",
                };
                return Json(datas);
            }
           
            catch (Exception ex)
            {
                var datas = new
                {
                      
                    msg ="导出失败："+ ex.Message,
                };
                return Json(datas);
            }
            
        }
          
        //表中有数据或无数据时使用,可排除DATASET不支持System.Nullable错误
        public  DataTable ConvertToDataSet<T>(IList<T> list)
        {
            //if (list == null || list.Count <= 0)
            ////return null;
            //{
            //    DataTable result = new DataTable();
            //    object temp;
            //    if (list.Count > 0)
            //    {
            //        PropertyInfo[] propertys = list[0].GetType().GetProperties();
            //        foreach (PropertyInfo pi in propertys)
            //        {
            //            //if (!(pi.Name.GetType() is System.Nullable))
            //            //if (pi!=null)
            //            {
            //                //pi = (PropertyInfo)temp;  
            //                result.Columns.Add(pi.Name, pi.PropertyType);
            //            }
            //        }
            //        for (int i = 0; i < list.Count; i++)
            //        {
            //            ArrayList tempList = new ArrayList();
            //            foreach (PropertyInfo pi in propertys)
            //            {
            //                object obj = pi.GetValue(list[i], null);
            //                tempList.Add(obj);
            //            }
            //            object[] array = tempList.ToArray();
            //            result.LoadDataRow(array, true);
            //        }
            //    }
            //    return result;
            //}
            //else
            //{
            //DataSet ds = new DataSet();
            DataTable dt = new DataTable(typeof(T).Name);
                DataColumn column;
                List<DataRow> row1=new List<DataRow>  ();
                DataRow row;
                System.Reflection.PropertyInfo[] myPropertyInfo =
                    typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
                foreach (T t in list)
                {
                    if (t == null) continue;
                    row = dt.NewRow();
                    for (int i = 0, j = myPropertyInfo.Length; i < j; i++)
                    {
                        System.Reflection.PropertyInfo pi = myPropertyInfo[i];
                        String name = pi.Name;
                        if (dt.Columns[name] == null)
                        {
                            if (pi.PropertyType.UnderlyingSystemType.ToString() == "System.Nullable`1[System.Int32]")
                            {
                                column = new DataColumn(name, typeof(Int32));
                                dt.Columns.Add(column);
                                //row[name] = pi.GetValue(t, new object[] {i});//PropertyInfo.GetValue(object,object[])
                                if (pi.GetValue(t, null) != null)
                                    row[name] = pi.GetValue(t, null);
                                else
                                    row[name] = System.DBNull.Value;
                            }
                            else
                            {
                                column = new DataColumn(name, pi.PropertyType);
                                dt.Columns.Add(column);
                                row[name] = pi.GetValue(t, null);
                            }
                        }
                        else {
                            row[name] = pi.GetValue(t, null);
                        
                        }
                    }
                    dt.Rows.Add(row);
                   
                }
                //ds.Tables.Add(dt);
                return dt;
            //}
        }
    }
}
